//
//  ComposeViewController.swift
//  Weibo8023
//
//  Created by styshy on 15/12/17.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    @objc private func close(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendStatus(){
        
        // 获取文本内容
        let text = textView.emoticonText
        
//        let image:UIImage = UIImage(named: "08")!
        let image = picturePickerController.pictures.last
        
        NetworkTools.sharedTools.sendStatus(text,image: image) { (result, error) -> () in
            if error != nil{
                print("出错了")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
//            print(result)
            // 关闭控制器
            self.close()
        }
    }
    
    @objc private func selectEmoticon(){
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        
        textView.becomeFirstResponder()
    }
    
    @objc private func selectPicture(){
        // 退掉键盘
        textView.resignFirstResponder()
        
        if picturePickerController.view.frame.height > 0 {
            return
        }
        
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
//    UIKeyboardAnimationCurveUserInfoKey = 7;
//    UIKeyboardAnimationDurationUserInfoKey = "0.25";
//    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {414, 271}}";
//    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {207, 871.5}";
//    UIKeyboardCenterEndUserInfoKey = "NSPoint: {207, 600.5}";
//    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 736}, {414, 271}}";
//    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 465}, {414, 271}}";
//    UIKeyboardIsLocalUserInfoKey = 1;
    // MARK: - 键盘处理
    @objc private func keyboardChanged(n:NSNotification){
        let dict:[String:AnyObject] = n.userInfo as! [String:AnyObject]
        // 动画时间
        let duration = (dict[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 动画曲线
        let curve = (dict[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        // 运动位置
        let keyFrame:CGRect = (dict[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offset:CGFloat = -UIScreen.mainScreen().bounds.height + keyFrame.origin.y
        
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    override func loadView() {
        view = UIView()
        
        setupUI()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 添加键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
        
        if picturePickerController.view.frame.height == 0{
            textView.becomeFirstResponder()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private lazy var toolbar:UIToolbar = UIToolbar()
    
    private lazy var textView:UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        
        tv.alwaysBounceVertical = true
        
        // scrollView在滚动的时候，退出键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.delegate = self
        
        return tv
        
    }()
    
    private lazy var placeHoderLabel:UILabel = UILabel(title: "分享新鲜事...",
        fontSize: 18, color: UIColor.lightGrayColor())
    
    private lazy var picturePickerController = PicturePickerController()
    
    private lazy var emoticonView:EmoticonView = EmoticonView { [weak self](emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    
}
// MARK: - UITextViewDelegate
extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHoderLabel.hidden = textView.hasText()
    }
}


extension ComposeViewController{
    private func setupUI(){
        
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor.whiteColor()
        
        prepareNavigationBar()
        prepareToolbar()
        
        // TODO: -textView布局&占位标签
        prepareTextView()
        preparePicturePicker()
    }
    
    // 设置照片选择控制器
    func preparePicturePicker(){
        // 添加子控制器
        addChildViewController(picturePickerController)
        
//        view.addSubview(picturePickerController.view)
        view.insertSubview(picturePickerController.view, belowSubview: toolbar)
        
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
//            make.height.equalTo(view.snp_right).multipliedBy(0.6)
            make.height.equalTo(0)
        }
    }
    
    // 设置textView
    private func prepareTextView(){
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        
        textView.addSubview(placeHoderLabel)
        placeHoderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    
    // 设置工具条
    private func prepareToolbar(){
        view.addSubview(toolbar)
        
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        
        // 添加按钮
        let itemSetting = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                    ["imageName": "compose_mentionbutton_background"],
                    ["imageName": "compose_trendbutton_background"],
                    ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                    ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSetting{
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: nil, actionName: dict["actionName"])
            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    /**
     准备导航条
     */
    private func prepareNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "sendStatus")
        
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        navigationItem.titleView = titleView
        
        // 设置标题视图
        let titleLabel = UILabel(title: "发微博", fontSize: 15, color: UIColor.darkGrayColor())
        let screenNameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.account?.screen_name ?? "", fontSize: 13, color: UIColor.lightGrayColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(screenNameLabel)
  
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        screenNameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
}




